package com.example.warehousems.controller;

import com.example.warehousems.component.BaseResponse;
import com.example.warehousems.component.UserInfo;
import com.example.warehousems.config.Constants;
import com.example.warehousems.dao.model.Cargo;
import com.example.warehousems.dao.model.JobTicket;
import com.example.warehousems.dao.model.User;
import com.example.warehousems.service.JobTicketService;
import com.example.warehousems.service.UserService;
import com.example.warehousems.vo.CargoVO;
import com.example.warehousems.vo.JobTicketVO;
import com.example.warehousems.vo.TicketAdviceVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/job-ticket")
@Slf4j
public class JobTicketController {
    @Autowired
    private UserService userService;
    @Autowired
    private JobTicketService jobTicketService;

    /*
     * generate a jobTicket
     * */
    @PostMapping("")
    BaseResponse<Integer> generateJobTicket(@RequestBody @Validated JobTicketVO jobTicketVO) {
        JobTicket jobTicket = new JobTicket();

        Integer proposerId = Integer.valueOf(UserInfo.get("id"));
        System.out.println("proposerId: " + proposerId);
        User proposer = userService.findUserById(proposerId);
        jobTicket.setProposer(proposer);
        jobTicket.setContactName(jobTicketVO.getContactName());
        jobTicket.setPhoneNum(jobTicketVO.getPhoneNum());
        jobTicket.setCreateTime(LocalDateTime.now());
        jobTicket.setEstimateTime(jobTicketVO.getEstimateTime());
        jobTicket.setStatus(Constants.JOBTICKETSTATUS.TO_CHECK);
        User admin = userService.findUserById(userService.findAdminId());
        jobTicket.setAdmin(admin);

        ArrayList<Cargo> cargos = new ArrayList<>();
        for (CargoVO cargoVO : jobTicketVO.getCargoList()) {
            Cargo cargo = new Cargo();
            cargo.setData(
                    cargoVO.getName(),
                    cargoVO.getLength(),
                    cargoVO.getWidth(),
                    cargoVO.getHeight(),
                    cargoVO.getWeight(),
                    cargoVO.getOutBranch()
            );
            cargo.setInTime(LocalDateTime.now());
            cargos.add(cargo);
        }

//        var res = warehouseService.putCargosIntoStorage(cargos);
        jobTicket.setCargoList(cargos);
        log.info("jobTicket: " + jobTicket);

        return BaseResponse.success(jobTicketService.generateJobTicket(jobTicket, cargos));
    }

    /**
     * 查询工单，管理员可看到所有工单，用户只能看到自己申请的工单
     */
    @GetMapping("")
    BaseResponse<List<JobTicket>> getJobTicket() {
        Integer userId = Integer.valueOf(UserInfo.get("id"));
        List<JobTicket> jobTickets = jobTicketService.getJobTicket(userId);
        return BaseResponse.success(jobTickets);
    }

    @GetMapping("/page/{pageNum}/{pageSize}")
    BaseResponse<List<JobTicket>> getJobTicket(@PathVariable("pageNum") Integer pageNum,
                                               @PathVariable("pageSize") Integer pageSize) {
        Integer userId = Integer.valueOf(UserInfo.get("id"));

        Pageable pageable = PageRequest.of(pageNum, pageSize);

        Page<JobTicket> jobTicketPage = jobTicketService.getJobTicket(userId, pageable);

        List<JobTicket> jobTicketList = jobTicketPage.getContent();

        return BaseResponse.success(jobTicketList);

    }

    @GetMapping("/{jobTicketId}")
    BaseResponse<JobTicket> getJobTicketById(@PathVariable("jobTicketId") Integer jobTicketId) {
        return BaseResponse.success(jobTicketService.getJobTicketById(jobTicketId));
    }

    /**
     * 管理员确认工单完成
     */
    @PatchMapping ("/{jobTicketId}/approvals")
    BaseResponse<String> confirm(@PathVariable("jobTicketId") Integer jobTicketId) {
        var res = jobTicketService.confirm(jobTicketId);
        if (res == Constants.COMMONSTATUS.SUCCESS)
            return BaseResponse.success("successful confirmation");
        else
            return BaseResponse.error("wrong operation");
    }

    /**
     * 管理员填写审核意见
     * @param ticketAdviceVO
     */
    @PutMapping("/approvals")
    BaseResponse<String> addSuggestion(@RequestBody TicketAdviceVO ticketAdviceVO) {
        Integer jobTicketId = ticketAdviceVO.getJobTicketId();
        Boolean isPassed = ticketAdviceVO.getStatus();
        String adminSug = ticketAdviceVO.getAdminSug();
        var res = jobTicketService.addSuggestion(jobTicketId, adminSug, isPassed);
        if (res == Constants.COMMONSTATUS.SUCCESS)
            return BaseResponse.success("suggestion changed");
        else
            return BaseResponse.error("wrong operation");
    }

    /**
     * 用户支付，修改状态
     * @param jobTicketId
     */
    @PostMapping("/{jobTicketId}/payment")
    BaseResponse<String> payment(@PathVariable("jobTicketId") Integer jobTicketId) {
        var res = jobTicketService.payment(jobTicketId);
        if (res == Constants.COMMONSTATUS.SUCCESS)
            return BaseResponse.success("successful payment");
        else
            return BaseResponse.error("wrong operation");
    }

    @DeleteMapping("/{jobTicketId}/payment")
    BaseResponse<String> cancelPayment(@PathVariable("jobTicketId") Integer jobTicketId) {
        var res = jobTicketService.cancelPayment(jobTicketId);
        if (res == Constants.COMMONSTATUS.SUCCESS)
            return BaseResponse.success("successful cancel");
        else
            return BaseResponse.error("wrong operation");
    }

    /**
     * 初步估计费用
     * @param cargoVOs
     */
    @PostMapping("/price")
    BaseResponse<Float> calCost(@RequestBody @Validated List<CargoVO> cargoVOs) {
        return BaseResponse.success(jobTicketService.calculatePrice(cargoVOs));
    }
}
